const express = require('express');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, asyncHandler } = require('../utils/response');
const { authenticateToken } = require('../utils/auth');

// 导入服务层
const statisticsService = require('../services/statisticsService');

/**
 * 获取学习统计
 * GET /statistics/study
 */
router.get('/study', authenticateToken, asyncHandler(async (req, res) => {
  const { period = 'week' } = req.query;
  const userId = req.user.id;
  
  // 验证周期参数
  const periodValidation = validateEnum(period, ['week', 'month', 'year'], '统计周期');
  if (!periodValidation.isValid) {
    return badRequest(res, periodValidation.message);
  }

  // 获取用户学习统计数据
  const studyStats = await fileDao.getUserStudyStatistics(userId);
  
  if (!studyStats) {
    // 如果没有统计数据，返回默认值
    const defaultStats = {
      totalStudyTime: 0,
      totalPractices: 0,
      averageScore: 0,
      continuousDays: 0,
      weeklyData: [],
      scoreDistribution: {
        excellent: 0,
        good: 0,
        average: 0,
        poor: 0
      },
      improvements: {
        accuracy: 0,
        fluency: 0,
        completeness: 0
      }
    };
    
    return success(res, defaultStats);
  }

  // 解析统计数据
  const weeklyData = studyStats.weekly_data ? JSON.parse(studyStats.weekly_data) : [];
  const monthlyData = studyStats.monthly_data ? JSON.parse(studyStats.monthly_data) : [];
  const scoreDistribution = studyStats.score_distribution ? JSON.parse(studyStats.score_distribution) : {
    excellent: 0,
    good: 0,
    average: 0,
    poor: 0
  };

  // 根据周期返回相应数据
  let periodData = [];
  if (period === 'week') {
    periodData = weeklyData.slice(-7); // 最近7天
  } else if (period === 'month') {
    periodData = monthlyData.slice(-30); // 最近30天
  } else if (period === 'year') {
    periodData = monthlyData.slice(-365); // 最近365天
  }

  // 计算改进率（与上个周期对比）
  const improvements = {
    accuracy: calculateImprovement(periodData, 'accuracy'),
    fluency: calculateImprovement(periodData, 'fluency'),
    completeness: calculateImprovement(periodData, 'completeness')
  };

  const responseData = {
    totalStudyTime: studyStats.total_study_time || 0,
    totalPractices: studyStats.total_practices || 0,
    averageScore: parseFloat(studyStats.average_score || 0).toFixed(1),
    continuousDays: studyStats.continuous_days || 0,
    weeklyData: periodData,
    scoreDistribution,
    improvements
  };

  success(res, responseData);
}));

/**
 * 获取详细学习报告
 * GET /statistics/report
 */
router.get('/report', authenticateToken, asyncHandler(async (req, res) => {
  const { period = 'month' } = req.query;
  const userId = req.user.id;
  
  // 验证周期参数
  const periodValidation = validateEnum(period, ['week', 'month', 'year'], '统计周期');
  if (!periodValidation.isValid) {
    return badRequest(res, periodValidation.message);
  }

  // 获取各模块的统计数据
  const [
    detectionStats,
    gameStats,
    dailyStats,
    courseStats
  ] = await Promise.all([
    detectionDao.getUserEvaluationStats(userId),
    gameDao.getUserGameStats(userId),
    dailyDao.getUserDailyStats(userId),
    getUserCourseStats(userId)
  ]);

  const report = {
    period,
    generatedAt: new Date().toISOString(),
    overview: {
      totalStudyTime: (detectionStats.totalStudyTime || 0) + (gameStats.totalStudyTime || 0) + (dailyStats.totalStudyTime || 0),
      totalActivities: (detectionStats.totalEvaluations || 0) + (gameStats.totalGames || 0) + (dailyStats.totalDays || 0),
      averageScore: calculateOverallAverageScore([detectionStats, gameStats, dailyStats])
    },
    modules: {
      detection: {
        name: '语音检测',
        totalPractices: detectionStats.totalEvaluations || 0,
        averageScore: parseFloat(detectionStats.averageScore || 0),
        bestScore: parseFloat(detectionStats.bestScore || 0),
        improvement: parseFloat(detectionStats.improvementRate || 0)
      },
      game: {
        name: '小游戏',
        totalGames: gameStats.totalGames || 0,
        averageScore: parseFloat(gameStats.averageScore || 0),
        bestScore: parseFloat(gameStats.bestScore || 0),
        todayGames: gameStats.todayGames || 0
      },
      daily: {
        name: '每日一句',
        continuousDays: dailyStats.continuousDays || 0,
        totalDays: dailyStats.totalDays || 0,
        averageScore: parseFloat(dailyStats.averageScore || 0),
        bestScore: parseFloat(dailyStats.bestScore || 0),
        thisMonthDays: dailyStats.thisMonthDays || 0
      },
      course: {
        name: '课程学习',
        enrolledCourses: courseStats.enrolledCourses || 0,
        completedCourses: courseStats.completedCourses || 0,
        totalStudyTime: courseStats.totalStudyTime || 0,
        averageProgress: parseFloat(courseStats.averageProgress || 0)
      }
    },
    achievements: {
      recentAchievements: [], // TODO: 从成就系统获取
      totalAchievements: 0,
      completionRate: 0
    },
    recommendations: generateLearningRecommendations(detectionStats, gameStats, dailyStats, courseStats)
  };

  success(res, report);
}));

/**
 * 获取学习排行榜
 * GET /statistics/leaderboard
 */
router.get('/leaderboard', asyncHandler(async (req, res) => {
  const { type = 'overall', period = 'month', limit = 10 } = req.query;
  
  // 验证类型参数
  const typeValidation = validateEnum(type, ['overall', 'detection', 'game', 'daily'], '排行榜类型');
  if (!typeValidation.isValid) {
    return badRequest(res, typeValidation.message);
  }

  // 验证周期参数
  const periodValidation = validateEnum(period, ['week', 'month', 'all'], '统计周期');
  if (!periodValidation.isValid) {
    return badRequest(res, periodValidation.message);
  }

  let leaderboard = [];

  switch (type) {
    case 'detection':
      leaderboard = await detectionDao.getEvaluationLeaderboard({ period, limit });
      break;
    case 'game':
      leaderboard = await gameDao.getGameLeaderboard({ period, limit });
      break;
    case 'daily':
      leaderboard = await dailyDao.getDailyLeaderboard({ period, limit });
      break;
    case 'overall':
    default:
      // 综合排行榜需要综合各模块数据
      leaderboard = await getOverallLeaderboard({ period, limit });
      break;
  }

  success(res, {
    type,
    period,
    leaderboard,
    updatedAt: new Date().toISOString()
  });
}));

/**
 * 获取学习趋势
 * GET /statistics/trends
 */
router.get('/trends', authenticateToken, asyncHandler(async (req, res) => {
  const { days = 30 } = req.query;
  const userId = req.user.id;
  
  const daysInt = Math.min(Math.max(parseInt(days) || 30, 7), 365); // 限制在7-365天之间

  // 获取用户学习统计数据
  const studyStats = await fileDao.getUserStudyStatistics(userId);
  
  if (!studyStats) {
    return success(res, {
      trends: [],
      summary: {
        totalDays: 0,
        activeDays: 0,
        averageScore: 0,
        totalStudyTime: 0
      }
    });
  }

  // 解析每日数据
  const dailyData = studyStats.weekly_data ? JSON.parse(studyStats.weekly_data) : [];
  const recentData = dailyData.slice(-daysInt);

  // 计算趋势数据
  const trends = recentData.map(day => ({
    date: day.date,
    studyTime: day.studyTime || 0,
    practiceCount: day.practiceCount || 0,
    averageScore: day.averageScore || 0,
    modules: {
      detection: day.detection || 0,
      game: day.game || 0,
      daily: day.daily || 0,
      course: day.course || 0
    }
  }));

  // 计算汇总数据
  const summary = {
    totalDays: recentData.length,
    activeDays: recentData.filter(day => day.practiceCount > 0).length,
    averageScore: recentData.length > 0 
      ? (recentData.reduce((sum, day) => sum + (day.averageScore || 0), 0) / recentData.length).toFixed(1)
      : 0,
    totalStudyTime: recentData.reduce((sum, day) => sum + (day.studyTime || 0), 0)
  };

  success(res, { trends, summary });
}));

// 辅助函数：计算改进率
function calculateImprovement(data, metric) {
  if (data.length < 2) return 0;
  
  const recent = data.slice(-7); // 最近7天
  const previous = data.slice(-14, -7); // 前7天
  
  if (recent.length === 0 || previous.length === 0) return 0;
  
  const recentAvg = recent.reduce((sum, day) => sum + (day[metric] || 0), 0) / recent.length;
  const previousAvg = previous.reduce((sum, day) => sum + (day[metric] || 0), 0) / previous.length;
  
  if (previousAvg === 0) return 0;
  
  return ((recentAvg - previousAvg) / previousAvg * 100).toFixed(1);
}

// 辅助函数：计算总体平均分
function calculateOverallAverageScore(statsArray) {
  const validStats = statsArray.filter(stat => stat && stat.averageScore);
  if (validStats.length === 0) return 0;
  
  const totalScore = validStats.reduce((sum, stat) => sum + parseFloat(stat.averageScore), 0);
  return (totalScore / validStats.length).toFixed(1);
}

// 辅助函数：获取用户课程统计
async function getUserCourseStats(userId) {
  try {
    // 这里应该调用课程DAO的统计方法
    // 现在返回模拟数据
    return {
      enrolledCourses: 5,
      completedCourses: 2,
      totalStudyTime: 3600,
      averageProgress: 65.5
    };
  } catch (error) {
    console.error('获取课程统计失败:', error);
    return {
      enrolledCourses: 0,
      completedCourses: 0,
      totalStudyTime: 0,
      averageProgress: 0
    };
  }
}

// 辅助函数：获取综合排行榜
async function getOverallLeaderboard(options) {
  try {
    // 这里应该综合各模块的数据计算综合排行榜
    // 现在返回模拟数据
    return [
      {
        rank: 1,
        userId: 1,
        username: 'user1',
        nickname: '学习达人',
        avatar: 'https://example.com/avatar1.jpg',
        overallScore: 95.5,
        totalActivities: 150
      }
    ];
  } catch (error) {
    console.error('获取综合排行榜失败:', error);
    return [];
  }
}

// 辅助函数：生成学习建议
function generateLearningRecommendations(detectionStats, gameStats, dailyStats, courseStats) {
  const recommendations = [];
  
  // 基于语音检测表现给出建议
  if (detectionStats.averageScore < 80) {
    recommendations.push({
      type: 'detection',
      title: '提升发音准确性',
      description: '您的语音检测平均分较低，建议多练习基础发音',
      action: '前往语音检测模块练习'
    });
  }
  
  // 基于游戏表现给出建议
  if (gameStats.todayGames < 3) {
    recommendations.push({
      type: 'game',
      title: '增加游戏练习',
      description: '今天的游戏练习次数较少，建议增加练习频率',
      action: '前往小游戏模块'
    });
  }
  
  // 基于每日一句给出建议
  if (dailyStats.continuousDays < 7) {
    recommendations.push({
      type: 'daily',
      title: '保持每日练习',
      description: '连续打卡天数较少，建议养成每日练习的习惯',
      action: '前往每日一句模块'
    });
  }
  
  return recommendations;
}

module.exports = router;
